package com.sita.tingterest.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.sita.bike.R;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Category;
import com.sita.bike.rest.model.ListResponseData;
import com.sita.tingterest.activity.MusicPlayGridViewActivity;
import com.sita.tingterest.activity.VideoAdapter;
import com.sita.tingterest.activity.VideoPlayActivity;
import com.sita.tingterest.adapter.MusicGridViewAdapter;
import com.sita.tingterest.pojo.Audio;
import com.sita.tingterest.pojo.CategoryRequest;
import com.sita.tingterest.pojo.Music;
import com.sita.tingterest.pojo.Pic;
import com.sita.tingterest.utils.L;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by RasInforays on 10/22/2015.
 */
public class FragmentRecommends extends BaseFragment2 implements View.OnClickListener, View.OnTouchListener {

    private ImageView mMusicIcon;
    private String SongUri = "http://get2.mymp3singer.com/files/ds58/28553/05_-_Jeena_Jeena_(Remix)-(MyMp3Singer.com).mp3";
    private TextView mMusicTitle;
    private TextView mMusicArtist;
    private ImageView mPreImageView;
    private ImageView mPlayImageView;
    private ImageView mNextImageView;
    MusicFragment musicFragment;
    Fragment objFragment;
    private SeekBar mMusicProgress;
    private boolean isPause;
    private Music music;
    private Pic pic;
    private Audio audio;
    private Category category;
    public ArrayList<Category> categoryList;
    private GridView gridView;
    public static ArrayList<Music> musicList;
    public static ArrayList<Pic> picArrayList;
    public static ArrayList<Audio> audioArrayList;
    public MusicGridViewAdapter gridViewAdapter;
    public PullToRefreshGridView pullToRefreshGridView;
    private int mediaFileLengthInMilliseconds;
    private TextView music_currwnt_position, music_Total_length;
    public String contents = null;
    public View rootView = null;
    public String name, id;
    public List<Category> mCategoryList;
    public RelativeLayout mLayout;
    public ImageView img_menu;
    public GridView mGridView;
    public VideoAdapter mVideoAdapter;

    @Override
    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
        super.dump(prefix, fd, writer, args);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.ting_fragment_recommends, container, false);
        mLayout = (RelativeLayout) rootView.findViewById(R.id.titleTingTrust);
        img_menu = (ImageView) rootView.findViewById(R.id.back_menu);
        mGridView = (GridView) rootView.findViewById(R.id.gridView_video);
        img_menu.setOnClickListener(this);
        mLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads()
                .detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
        L.l("MY TAG", "onCreateView" + "  ..Fragment Recommends;");
        getNetworkJsonData();
        return rootView;
    }

    public void getNetworkJsonData() {
        CategoryRequest categoryRequest = new CategoryRequest();
        categoryRequest.mAccountId = "1";
        RestClient.getRestService().categoryList(categoryRequest, new Callback<ListResponseData>() {
            @Override
            public void success(ListResponseData listResponseData, Response response) {
                if (response.getStatus() == 200) {
                    if (listResponseData.mErrorCode.equals("0") && listResponseData.mData != null) {
                        try {
                            mCategoryList = listResponseData.mData;
                            setGridView(rootView);
                        } catch (Exception e) {
                            Log.i("MyTag", "" + e);
                        }
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(getActivity(), "请求数据失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }


    private void setGridView(View rooView) {
        mVideoAdapter = new VideoAdapter(getActivity());
        gridViewAdapter = new MusicGridViewAdapter(getActivity(), mCategoryList);
        pullToRefreshGridView = (PullToRefreshGridView) rooView.findViewById(R.id.gridView1);
        //设置Mode为支持上拉加载下拉刷新
        pullToRefreshGridView.setMode(PullToRefreshBase.Mode.BOTH);
        //设置下拉刷新标题
        pullToRefreshGridView.getLoadingLayoutProxy(true, false).setPullLabel("正在刷新。。");
        pullToRefreshGridView.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在刷新。。");
        pullToRefreshGridView.getLoadingLayoutProxy(true, false).setReleaseLabel("刷新。。。");
        //设置上拉加载标题
        pullToRefreshGridView.getLoadingLayoutProxy(false, true).setPullLabel("正在加载");
        pullToRefreshGridView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在努力加载");
        pullToRefreshGridView.getLoadingLayoutProxy(false, true).setReleaseLabel("放手加载更多");
        pullToRefreshGridView.setAdapter(gridViewAdapter);
        mGridView.setAdapter(mVideoAdapter);

        pullToRefreshGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                Intent intent = new Intent(getActivity(), MusicPlayGridViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("catId", mCategoryList.get(position).mId);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), VideoPlayActivity.class);
                startActivity(intent);
            }
        });
    }

    private void setView(View layout) {
        mMusicIcon = (ImageView) layout.findViewById(R.id.iv_play_icon);
        mMusicTitle = (TextView) layout.findViewById(R.id.tv_play_title);
        mMusicArtist = (TextView) layout.findViewById(R.id.tv_play_artist);
        mPreImageView = (ImageView) layout.findViewById(R.id.iv_pre);
        mPlayImageView = (ImageView) layout.findViewById(R.id.iv_play);
        mNextImageView = (ImageView) layout.findViewById(R.id.iv_next);
        mMusicProgress = (SeekBar) layout.findViewById(R.id.play_progress);
        music_currwnt_position = (TextView) layout.findViewById(R.id.music_current_postion);
        music_Total_length = (TextView) layout.findViewById(R.id.music_total_length);
    }


    @Override
    public void onStart() {
        super.onStart();
        L.l("MY TAG", "onStart()" + "  ..Fragment Recommends;");

    }

    @Override
    public void onResume() {
        allowBindService();
        super.onResume();

        isPause = false;
        L.l("MY sr", "onResume()" + "  ..Fragment Recommends;");
    }

    @Override
    public void onPause() {
        allowUnbindService();
        isPause = true;
        L.l("MY sr", "onPause()" + "  ..Fragment Recommends;");
        super.onPause();
    }

    /**
     * stop时， 回调通知activity解除绑定服务
     */
    @Override
    public void onStop() {
        super.onStop();
        L.l("MY TAG", "On STop" + "  ..Fragment Recommends;");

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (v.getId() == R.id.play_progress) {
            if (mPlayService.isPlaying()) {
                SeekBar sb = (SeekBar) v;
                int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
                mPlayService.seek(playPositionInMillisecconds);
            }
        }
        return false;
    }

    @Override
    protected void onChange(int position) {

    }

    @Override
    protected void onPublish(int progress) {

        mediaFileLengthInMilliseconds = mPlayService.getDuration();
        L.l("MY sr", "onPublish(int progress)" + "  .. mediaFileLengthInMilliseconds" + mediaFileLengthInMilliseconds);
        mMusicProgress.setProgress((int) (((float) progress / mediaFileLengthInMilliseconds) * 100));

    }

    private void onPlay(int position) {
        if (!mPlayService.isPlaying()) {
            mPlayService.play(position);
            mPlayImageView.setImageResource(android.R.drawable.ic_media_pause);
        } else {
            mPlayService.pausePlayer();
            mPlayImageView.setImageResource(android.R.drawable.ic_media_play);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_play_icon:
                Bundle bundle = new Bundle();
                bundle.putString("SongUri", music.getAudio().getUrl());
                objFragment = new Fragment();
                musicFragment = new MusicFragment();
                musicFragment.setArguments(bundle);
                objFragment = musicFragment;
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                // fragmentTransaction.replace(R.id.container,objFragment,"FragmentRecommends").addToBackStack("FmRecoomends").commit();
                // Toast.makeText(getContext(), "IV_PLAY_ICON_CLICK", Toast.LENGTH_LONG).show();
                break;
            case R.id.iv_play:
                // Toast.makeText(getContext(),"iv_play:",Toast.LENGTH_LONG).show();
                if (mPlayService.isPlaying()) {
                    mPlayService.pausePlayer(); // 暂停
                    mPlayImageView.setImageResource(android.R.drawable.ic_media_play);
                } else {
                    //onPlay(mPlayService.getCurrentPosition()); // 播放
                    mPlayService.start();
                    mPlayImageView.setImageResource(android.R.drawable.ic_media_pause);
                }
                break;
            case R.id.iv_next:
                mPlayService.next(); // 下一曲
                //Toast.makeText(getContext(), "next()", Toast.LENGTH_LONG).show();
                //getPlayService().next(); // 下一曲
                break;
            case R.id.iv_pre:
                mPlayService.pre(); // 上一曲
                //Toast.makeText(getContext(),"iv_pre",Toast.LENGTH_LONG).show();
                //getPlayService().pre(); // 上一曲
                break;
            case R.id.back_menu:
//                SlidingFragmentActivity s = (SlidingFragmentActivity) getActivity();
//                s.getSlidingMenu().toggle();
                break;
        }
    }
}

